package com.doubao.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * JWT验证过滤器
 */
@Slf4j
@Component
public class JwtAuthFilter implements GlobalFilter, Ordered {

    // 使用一个简单的密钥，在实际环境中应该从配置中心获取
    private static final String SECRET_KEY = "DoubaoAuthServiceJwtSecretKey0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    // 对于JJWT 0.11.x，需要使用不同的方式创建密钥
    private static final SecretKey JWT_SECRET_KEY = Keys.hmacShaKeyFor(SECRET_KEY.getBytes(StandardCharsets.UTF_8));

    private final ObjectMapper objectMapper = new ObjectMapper();

    // 白名单路径
    private final List<String> whitelist = new ArrayList<>();

    private final AntPathMatcher pathMatcher = new AntPathMatcher();

    public JwtAuthFilter() {
        // 添加不需要验证的路径
        whitelist.add("/auth/**");
        whitelist.add("/auth/login");
        whitelist.add("/auth/register");
        whitelist.add("/auth/refresh-token");
        whitelist.add("/auth/send-code");
        whitelist.add("/auth/phone-login");
        whitelist.add("/auth/wx-login");
        whitelist.add("/file/public/**");
        whitelist.add("/wechat/callback/**");
        whitelist.add("/user/register");
        whitelist.add("/user/login");
        // 调试时可以临时将用户信息接口添加到白名单
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();

        log.debug("请求路径: {}", path);

        // 检查是否是白名单路径
        if (isWhitelistPath(path)) {
            log.debug("白名单路径，跳过验证: {}", path);
            return chain.filter(exchange);
        }

        // 获取Authorization头
        String authorization = request.getHeaders().getFirst("Authorization");

        // 检查Authorization是否存在
        if (!StringUtils.hasText(authorization)) {
            log.debug("请求缺少Authorization头: {}", path);
            return unauthorized(exchange, "Missing JWT token");
        }

        // Bearer token格式验证
        if (!authorization.startsWith("Bearer ")) {
            log.debug("JWT格式错误: {}", authorization);
            return unauthorized(exchange, "Invalid JWT token format");
        }

        // 提取token
        String token = authorization.substring(7);

        try {
            // 添加调试日志 - 开始验证令牌
            log.debug("开始验证JWT令牌: {}", token);
            // 验证JWT token
            Claims claims = Jwts.parserBuilder()
                    .setSigningKey(JWT_SECRET_KEY)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();

            // 添加调试日志 - 验证成功，记录所有声明
            log.debug("JWT令牌验证成功，所有声明: {}", claims);

            // 从token中提取用户ID
            String userId = claims.get("userId", String.class);
            log.debug("从令牌中提取用户ID: {}", userId);

            // 将用户ID添加到请求头
            ServerHttpRequest mutatedRequest = request.mutate()
                    .header("X-User-ID", userId)
                    .build();

            log.debug("添加用户ID到请求头: X-User-ID={}", userId);

            // 将修改后的请求传递给下一个过滤器
            return chain.filter(exchange.mutate().request(mutatedRequest).build());

        } catch (Exception e) {
            // 添加更详细的错误日志
            log.error("JWT验证失败: {} - 异常类型: {}", e.getMessage(), e.getClass().getName());
            return unauthorized(exchange, "Invalid JWT token");
        }
    }

    /**
     * 检查路径是否在白名单中
     */
    private boolean isWhitelistPath(String path) {
        return whitelist.stream()
                .anyMatch(pattern -> pathMatcher.match(pattern, path));
    }

    /**
     * 返回未授权响应
     */
    private Mono<Void> unauthorized(ServerWebExchange exchange, String message) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");

        Map<String, Object> result = new HashMap<>();
        result.put("code", 401);
        result.put("message", message);

        try {
            byte[] bytes = objectMapper.writeValueAsBytes(result);
            DataBuffer buffer = response.bufferFactory().wrap(bytes);
            return response.writeWith(Mono.just(buffer));
        } catch (JsonProcessingException e) {
            log.error("Error writing response", e);
            return response.setComplete();
        }
    }

    @Override
    public int getOrder() {
        // 在所有过滤器之前执行
        return -100;
    }
}